const encoding = require('../utils/ble/encoding.js')
import wxApplet from '../utils/wxApplet/wxApplet.js'

export const bluetooth = {
	data() {
		return {
			bluetooth_data: { //蓝牙数据
				deviceId: '',
				serviceId: '',
				characteristicId: '',
			},
			print_data: { //打印数据
				num: 1, //打印数量
				shop_id: '', //门店ID
				name: '', //姓名
				phone: '', //电话
				remark: '', //备注
				order_num: '', //订单编号
				id: '', //订单号
				qh_code: '', //取货码
			},
		}
	},

	methods: {
		initBluetooth(e) { //初始化蓝牙
			wxApplet.getBluetooth().then(res => {
				wx.openBluetoothAdapter({
					success: (res) => {
						// console.log('初始化');
						this.searchBluetooth(e);
					},
					fail: (err) => {
						uni.$u.toast('请检查手机蓝牙是否打开,或是否授权')
					}
				})
			})
		},
		searchBluetooth(e) { //开始搜寻附近的蓝牙外围设备
			wx.startBluetoothDevicesDiscovery({
				allowDuplicatesKey: false,
				success: (res) => {
					this.searchBluetoothList(e);
				},
			})
		},
		stopBluetooth() { //停止搜寻附近的蓝牙外围设备
			wx.stopBluetoothDevicesDiscovery({
				success: (res) => {
					// console.log(res)
				}
			})
		},
		searchBluetoothList(e) { //获取在蓝牙模块生效期间所有搜索到的蓝牙设备列表。包括已经和本机处于连接状态的设备。
			wx.getBluetoothDevices({
				success: (res) => {
					// console.log('蓝牙列表', res);
					for (let i = 0; i < res.devices.length; i++) {
						if (res.devices[i].localName && res.devices[i].localName.indexOf('WF610BLE') !=
							-1) {
							this.bluetooth_data.deviceId = res.devices[i].deviceId
							this.connectBluetooth(e)
							break;
						}
					}
				}
			})
		},
		connectBluetooth(e) { //连接蓝牙低功耗设备。
			wx.showLoading({
				title: '连接中...',
				mask: true
			})
			wx.createBLEConnection({
				deviceId: this.bluetooth_data.deviceId,
				success: (res) => {
					this.stopBluetooth(); //连接成功停止搜索蓝牙
					uni.$u.toast('连接成功')
					this.getserviceId(e)
				},
				fail: (res) => {
					if (res.errCode == -1) { //已连接
						this.getserviceId(e)
					} else {
						uni.$u.toast('连接失败')
					}
				},
				complete: (res) => {
					wx.hideLoading();
				}
			})
		},
		// 连接上需要的蓝牙设备之后，获取这个蓝牙设备的服务uuid  serviceId
		getserviceId(e) {
			wx.getBLEDeviceServices({
				deviceId: this.bluetooth_data.deviceId,
				success: (res) => {
					// console.log('serviceId', res);
					this.bluetooth_data.serviceId = res.services[1].uuid
					this.getCharacteId(e)
				}
			})
		},

		getCharacteId(e) { //获取蓝牙低功耗设备某个服务中所有特征 characteristic
			wx.getBLEDeviceCharacteristics({
				deviceId: this.bluetooth_data.deviceId,
				serviceId: this.bluetooth_data.serviceId,
				success: (res) => {
					// console.log("characteristic", res);
					for (var i = 0; i < res.characteristics.length; i++) {
						let item = res.characteristics[i];
						if (item.properties.indicate || item.properties.notify) {
							this.bluetooth_data.characteristicId = item.uuid
							this.startNotice(e) //7.0
							break;
						}
					}
				}
			})
		},

		startNotice(e) { //启用蓝牙低功耗设备特征值变化时的 notify 功能
			wx.notifyBLECharacteristicValueChange({
				state: true, // 启用 notify 功能
				deviceId: this.bluetooth_data.deviceId,
				serviceId: this.bluetooth_data.serviceId,
				characteristicId: this.bluetooth_data.characteristicId,
				success: (res) => {
					console.log(e, '标识符');
					if (e) {
						this.writeBluetooth()
					}
				}
			})
		},
		sleep(delay) { //延时
			var start = (new Date()).getTime();
			while ((new Date()).getTime() - start < delay) {
				continue;
			}
		},

		writeBluetooth() { //转二进制数据 
			let str =
				`CLS\r\nSET CUTTER 1\r\nCODEPAGE 936\r\nTEXT 460,30,"STZHONGS.TTF",90,8,8,"N0:${this.print_data.shop_id} ${this.print_data.name}  电话：${this.print_data.phone}"\r\nTEXT 380,30,"STZHONGS.TTF",90,9,9,"备注："\r\nBOX 180,110,50,495,2\r\nBLOCK 410,120,370,220,"STZHONGS.TTF",90,8,8,0,1,"${this.print_data.remark}"\r\nTEXT 35,30,"STZHONGS.TTF",90,8,8,"订单编号：${this.print_data.order_num}  提货码：${this.print_data.qh_code}"\r\nQRCODE 190,535,H,7,M,90,M2,S7,"Aid${this.print_data.id}"\r\nPUTBMP 25,710,"logo.BMP"\r\nPRINT 1,${this.print_data.num}\r\n`
			let buffer = new encoding.TextEncoder("gb2312", {
				NONSTANDARD_allowLegacyEncoding: true
			}).encode(str).buffer

			let byteLen = buffer.byteLength; //长度
			let pos = 0; //字符位置
			let tempBuffer; //一次发送的数据
			var i = 0;
			while (byteLen > 0) {
				i++;
				if (byteLen > 18) {
					tempBuffer = buffer.slice(pos, pos + 18);
					pos += 18;
					byteLen -= 18;
					console.log("第", i, "次发送:", tempBuffer);
					this.sleep(0.02)
					this.sendBluetooth(tempBuffer);
				} else {
					tempBuffer = buffer.slice(pos, pos + byteLen);
					pos += byteLen;
					byteLen -= byteLen;
					console.log("第", i, "次发送:", tempBuffer);
					this.sleep(0.02)
					this.sendBluetooth(tempBuffer);
				}
			}

		},
		sendBluetooth(e) { //向蓝牙低功耗设备特征值中 写入二进制数据
			wx.writeBLECharacteristicValue({
				deviceId: this.bluetooth_data.deviceId,
				serviceId: this.bluetooth_data.serviceId,
				characteristicId: this.bluetooth_data.characteristicId,
				value: e,
				success: (res) => {
					console.log("Success", res);
				},
				fail: (res) => {
					console.log("Fail", res);
				}
			})
		},
	}
}
